#!/usr/bin/env python3

import datetime
import os
import pathlib
from flask import Flask, request, render_template

app = Flask(__name__)
log_filename = f"{datetime.datetime.now().strftime('%Y%m%d_%H')}.log"

log_dir = pathlib.Path().home() / "flask_chatroom_logs"
if not log_dir.exists():
    log_dir.mkdir()
log_filename = os.path.join(log_dir, log_filename)

messages = []


@app.before_request
def print_request_info():
    print(f"writing to {log_filename}:\n{request}")
    with open(log_filename, mode="w") as fd:
        print(request.url, file=fd)


@app.route("/", methods=["GET"])
def index():
    return render_template("index.html", messages=messages)


@app.route("/", methods=["POST"])
def send_message():
    with open(log_filename, "a") as temp_log_fd:
        message_raw = request.form["message"]
        message = message_raw.split(":")[-1]
        print(message)
        print(message, file=temp_log_fd)
        message_raw = f"{request.remote_addr}:{message_raw}"
        print("#" + message_raw, file=temp_log_fd)
        print(message_raw)
    messages.append(message_raw)
    # return None
    return render_template("index.html", messages=messages)


@app.route("/message", methods=["GET"])
def show():
    return str(messages)


if __name__ == "__main__":
    with open(log_filename, "w") as log_fd:
        pass
    app.run(debug=True, host="0.0.0.0")
